package com.jetinno.jetinnosystem;

import android.app.IntentService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by zhangyuncai.
 * Date: 2022/2/15
 */
public class JetinnoSystemService extends IntentService {
    private static final String TAG = "JetinnoSystemService";

    private static Intent dogIntent = null;
    private int versionCode = 0;
    private int jetinnoCoffeeHbInterval = 0;//收到主APP心跳的时间间隔
    private SharedPreferences sharedPreferences;
    private JetinnoCoffeeHeatBeatReceiver jetinnoCoffeeHeatBeatReceiver;
    private boolean isRunning = true;

    public static void startService(Context context) {
        DogLog.logOperation(context, "startService,dogIntent==null:" + (dogIntent == null));
        DogLog.e(TAG, "startService");
        if (dogIntent != null) {
            stopService(context);
        }
        DogLog.logOperation(context, "startService");
        dogIntent = new Intent(context, JetinnoSystemService.class);
        context.startService(dogIntent);

    }

    public static void stopService(Context context) {
        DogLog.logOperation(context, "stopService");
        if (dogIntent != null) {
            context.stopService(dogIntent);
            dogIntent = null;
        }
    }

    public JetinnoSystemService() {
        super(TAG);
    }

    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 是否打开看门狗功能
     * 默认关闭
     *
     * @return
     */
    private boolean isStartJetinnoCoffeeApp() {
        try {
            return sharedPreferences.getBoolean("startJetinnoCoffeeApp", false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private void setStartJetinnoCoffeeApp(boolean startJetinnoCoffeeApp) {
        try {
            sharedPreferences.edit().putBoolean("startJetinnoCoffeeApp", startJetinnoCoffeeApp).apply();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onHandleIntent(Intent intent2) {
        DogLog.e(TAG, "onHandleIntent");
        DogLog.logOperation(getApplicationContext(), "onHandleIntent");
        versionCode = getVersionCode();

        sharedPreferences = getSharedPreferences("JetinnoSystem", Context.MODE_PRIVATE);

        jetinnoCoffeeHeatBeatReceiver = new JetinnoCoffeeHeatBeatReceiver();

        IntentFilter filter = new IntentFilter();
        //网络消息
        filter.addAction(HbConstant.JETINNO_COFFEE_HB_ACTION);
        registerReceiver(jetinnoCoffeeHeatBeatReceiver, filter);

        while (true) {//死循环心跳线程
            //对外发送心跳
            sendJetinnoSystemHb();

            if (isStartJetinnoCoffeeApp()) {
                jetinnoCoffeeHbInterval++;
                if (jetinnoCoffeeHbInterval > 30) {//超过一定时间,没有收到收到主APP心跳消息,启动主APP
                    jetinnoCoffeeHbInterval = 0;
                    startJetinnoCoffeeApp();

                }

            } else {//不需要启动主APP
                Log.e(TAG, "不需要启动主APP");
                jetinnoCoffeeHbInterval = 0;
            }

            if (!isRunning) {
                return;
            }
            SystemClock.sleep(1000);
            if (!isRunning) {
                return;
            }
        }
    }

    ///启动主APP
    private void startJetinnoCoffeeApp() {
        DogLog.logOperation(getApplicationContext(), "startJetinnoCoffeeApp");
        Log.e(TAG, "看门狗启动主APP");
        Intent intent = getApplicationContext().getPackageManager().getLaunchIntentForPackage(HbConstant.JETINNO_COFFEE_PACKAGE_NAME);
        if (intent != null) {//已安装APP
            jetinnoCoffeeHbInterval = -(5 * 60);//5分钟内只允许启动一次
            DogLog.logOperation(getApplicationContext(), "已安装主APP");
            forceStop();
            SystemClock.sleep(2000);
            new Handler(Looper.getMainLooper()).post(() -> {
                Toast.makeText(this, "start jetinno app !!", Toast.LENGTH_SHORT).show();
            });
            intent.putExtra(HbConstant.LAUNCH_SOURCE, HbConstant.JETINNO_SYSTEM_PACKAGE_NAME);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getApplicationContext().startActivity(intent);
        } else {//未安装APP,关闭自拉起功能
            DogLog.logOperation(getApplicationContext(), "未安装主APP");
            setStartJetinnoCoffeeApp(false);
        }
    }

    ///发送看门狗存活心跳
    private void sendJetinnoSystemHb() {
        DogLog.e(TAG, "versionCode:" + versionCode + ",sendDogAliveHb,mainHbInterval:" + jetinnoCoffeeHbInterval);
        Intent intent = new Intent(HbConstant.JETINNO_SYSTEM_HB_ACTION);
        intent.putExtra(HbConstant.JETINNO_SYSTEM_VERSION_CODE, versionCode);
        sendBroadcast(intent);
    }

    private int getVersionCode() {
        try {
            return getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 接受主APP心跳消息
     */
    private class JetinnoCoffeeHeatBeatReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e(TAG, "action:" + action);
            if (TextUtils.equals(action, HbConstant.JETINNO_COFFEE_HB_ACTION)) {//收到主APP的心跳
                jetinnoCoffeeHbInterval = 0;
                if (intent.hasExtra(HbConstant.IS_START_JETINNO_COFFEE)) {
                    boolean openDog = intent.getBooleanExtra(HbConstant.IS_START_JETINNO_COFFEE, true);
                    setStartJetinnoCoffeeApp(openDog);
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        isRunning = false;
        super.onDestroy();
        if (jetinnoCoffeeHeatBeatReceiver != null) {
            unregisterReceiver(jetinnoCoffeeHeatBeatReceiver);
        }
    }

    public static final String SIMPLE_CMD_FORCE_STOP = "am force-stop com.jinuo.mhwang.jetinnocoffe  \n";//停止主APP

    public void forceStop() {
        DogLog.logOperation(getApplicationContext(), "退出主APP");
        excuteCmd(SIMPLE_CMD_FORCE_STOP);
    }

    public void excuteCmd(String cmd) {
        Process process = null;
        OutputStream out = null;
        try {
            process = Runtime.getRuntime().exec("su");
            out = process.getOutputStream();
            try {
                out.write(cmd.getBytes());
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            process = null;
        }
    }
}
